<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>手势配置</title>
    <link rel="stylesheet" href="/static/style.css">
    <link rel="stylesheet" href="/static/gesture_config.css">
</head>
<body>
    <!-- 侧边栏 -->
    <div class="sidebar">
        <div class="sidebar-header">
            <div class="sidebar-title">
                智能工业手势识别
            </div>
           <div class="user-info">
                <span class="username">{{ current_user.username }}</span>
                <a href="{{ url_for('auth.logout_route') }}" class="logout">退出登录</a>
            </div>
        </div>
        <ul class="nav-menu">
            {% if session.role != 'admin' %}
              <li class="nav-item" onclick="window.location.href='{{ url_for('main.profile') }}'">个人信息</li>
            <li class="nav-item" onclick="window.location.href='{{ url_for('gesture.recognition') }}'">实时识别</li>
            <li class="nav-item active">手势配置</li>
            <li class="nav-item" onclick="window.location.href='{{ url_for('gesture.history') }}'">历史记录</li>
            {% else %}
            <li class="nav-item" onclick="window.location.href='{{ url_for('user.user_management') }}'">角色管理</li>
            <li class="nav-item" onclick="window.location.href='{{ url_for('user.user_records') }}'">识别记录</li>
            {% endif %}
        </ul>
    </div>

    <!-- 主内容区域 -->
    <div class="main-content">
        <div class="main-container">
            <div class="config-header">
                <h1>
                    <i class="fas fa-hand-point-up"></i>
                    手势配置
                </h1>
                <div class="config-description">
                    <i class="fas fa-info-circle"></i>
                    为每个手势配置对应的指令内容，让系统能够准确识别并执行您的指令
                </div>
            </div>

            <div class="config-container">
                <div class="config-list">
                    {% for i in range(1, 6) %}
                    <div class="config-item">
                        <div class="gesture-preview">
                            <div class="gesture-number">
                                <i class="fas fa-hand-point-up"></i>
                                手势 {{ i }}
                            </div>
                            <div class="gesture-image">
                                <img src="/static/gestures/gesture{{ i }}.jpg" alt="手势{{ i }}">
                            </div>
                        </div>
                        <div class="gesture-config">
                            <div class="input-group">
                                <label for="gesture-{{ i }}">
                                    <i class="fas fa-keyboard"></i>
                                    指令内容
                                </label>
                                <input type="text"
                                       id="gesture-{{ i }}"
                                       class="gesture-input"
                                       placeholder="请输入手势{{ i }}对应的指令"
                                       value="{{ contents[i|string] if contents[i|string] else '' }}">
                            </div>
                            <div class="video-upload">
                                <label for="video-{{ i }}" class="video-upload-label">
                                    <i class="fas fa-video"></i>
                                    上传视频
                                </label>
                                <input type="file"
                                       id="video-{{ i }}"
                                       class="video-input"
                                       accept="video/*"
                                       onchange="handleVideoUpload({{ i }}, this)">
                                <div class="video-preview" id="video-preview-{{ i }}">
                                    {% if contents[i|string] and contents[i|string].startswith('video:') %}
                                    <video controls>
                                        <source src="{{ contents[i|string].replace('video:', '') }}" type="video/mp4">
                                    </video>
                                    {% endif %}
                                </div>
                            </div>
                            <button class="save-btn" onclick="saveGesture({{ i }})" id="save-btn-{{ i }}">
                                <i class="fas fa-save"></i>
                                保存配置
                            </button>
                        </div>
                    </div>
                    {% endfor %}
                </div>
            </div>
        </div>
    </div>

    <!-- 保存成功提示 -->
    <div class="save-success" id="save-success">
        <i class="fas fa-check-circle"></i>
        <span>保存成功</span>
    </div>

    <style>
    .video-upload {
        margin: 10px 0;
    }

    .video-upload-label {
        display: inline-block;
        padding: 8px 16px;
        background-color: #4CAF50;
        color: white;
        border-radius: 4px;
        cursor: pointer;
        transition: background-color 0.3s;
    }

    .video-upload-label:hover {
        background-color: #45a049;
    }

    .video-input {
        display: none;
    }

    .video-preview {
        margin-top: 10px;
        max-width: 300px;
    }

    .video-preview video {
        width: 100%;
        border-radius: 4px;
    }
    </style>

    <script>
        function showSuccessMessage() {
            const successMessage = document.getElementById('save-success');
            successMessage.classList.add('show');
            setTimeout(() => {
                successMessage.classList.remove('show');
            }, 3000);
        }

        function setLoading(gestureNumber, isLoading) {
            const saveBtn = document.getElementById(`save-btn-${gestureNumber}`);
            if (isLoading) {
                saveBtn.classList.add('loading');
                saveBtn.disabled = true;
            } else {
                saveBtn.classList.remove('loading');
                saveBtn.disabled = false;
            }
        }

        function saveGesture(gestureNumber) {
            const input = document.getElementById(`gesture-${gestureNumber}`);
            const content = input.value.trim();

            if (!content) {
                alert('请输入手势指令内容');
                return;
            }

            setLoading(gestureNumber, true);

            fetch('{{ url_for('gesture.receive_content_route') }}', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    gesture: gestureNumber.toString(),
                    content: content
                })
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    showSuccessMessage();
                } else {
                    alert('保存失败：' + data.error);
                }
            })
            .catch(error => {
                alert('保存失败：' + error);
            })
            .finally(() => {
                setLoading(gestureNumber, false);
            });
        }

        function handleVideoUpload(gestureNumber, input) {
            const file = input.files[0];
            if (!file) return;

            // 检查文件类型
            if (!file.type.startsWith('video/')) {
                alert('请上传视频文件');
                return;
            }

            // 检查文件大小（限制为50MB）
            if (file.size > 50 * 1024 * 1024) {
                alert('视频文件大小不能超过50MB');
                return;
            }

            const formData = new FormData();
            formData.append('video', file);
            formData.append('gesture', gestureNumber.toString());

            setLoading(gestureNumber, true);

            fetch('{{ url_for('gesture.upload_video_route') }}', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    // 更新视频预览
                    const preview = document.getElementById(`video-preview-${gestureNumber}`);
                    preview.innerHTML = `<video controls><source src="${data.video_url}" type="video/mp4"></video>`;
                    
                    // 更新输入框内容
                    const input = document.getElementById(`gesture-${gestureNumber}`);
                    input.value = `video:${data.video_url}`;
                    
                    showSuccessMessage();
                } else {
                    alert('上传失败：' + data.error);
                }
            })
            .catch(error => {
                alert('上传失败：' + error);
            })
            .finally(() => {
                setLoading(gestureNumber, false);
            });
        }

        // 添加输入框焦点效果
        document.querySelectorAll('.gesture-input').forEach(input => {
            input.addEventListener('focus', () => {
                input.parentElement.parentElement.classList.add('focused');
            });

            input.addEventListener('blur', () => {
                input.parentElement.parentElement.classList.remove('focused');
            });
        });
    </script>
</body>
</html>
